<template>
  <el-container>
    <el-main>
      <el-form ref="warehouseForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">销售出库单</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="10">
            <el-form-item label="客户名称" prop="memberId">
              <el-select style="width: 100%" v-model="memberName" value-key="id" filterable placeholder="请选择"
                         @change="selectMember">
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="#" label="--- 新增品牌 ---"
                           value="#"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.createDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="所属仓库" prop="memberId">
              <el-select style="width: 100%" v-model="memberName" value-key="id" filterable placeholder="请选择"
                         @change="selectMember">
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="#" label="--- 新增品牌 ---"
                           value="#"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开票类型">
              <el-select style="width: 100%" v-model="form.taxType" placeholder="请选择状态">
                <el-option label="不开票" value="0"></el-option>
                <el-option label="增票" value="1"></el-option>
                <el-option label="普票" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="所属部门">
              <el-input v-model="officeName" suffix-icon="el-icon-search" @focus="dialogShow"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="仓管员">
              <el-select style="width: 100%" v-model="operatorName" filterable placeholder="请选择"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="收货人" prop="consignee">
              <el-input v-model="form.consignee"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="买家留言">
              <el-input v-model="form.memo"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="10">
            <el-form-item label="收货地址" prop="areaId">
              <Distpicker @selected="onSelected" :province="district.province" :city="district.city"
                          :area="district.area"></Distpicker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="详细地址">
              <div style="width: 100%;display: flex">
                <el-input v-model="form.address"/>
                <el-button style="margin-left: 10px" v-show="form.memberId !=''" @click="loadReceiver" type="primary"
                           icon="el-icon-more"></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
          <div style="display: flex;padding-top: 10px;padding-bottom: 10px">
            <el-input v-model="query.sn" placeholder="请输入货号" @change="queryClick"></el-input>
            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"
                       @click="moreProductClick">添加商品
            </el-button>
          </div>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名"
            width="200">
            <template slot-scope="{row}">
              <el-select v-model="row.name" filterable placeholder="请选择" @change="selectClick" @focus="tableClick(row)">
                <el-option
                  v-for="(item,index) in listForm"
                  :key="index"
                  :label="item.name"
                  :value="index"
                >
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="#" label="--- 新增品牌 ---"
                           value="#"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            width="100"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="100"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            width="100">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.quantity"/>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            width="100">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.price"/>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="100"
            align="right"
            prop="subTotal"
          >
          </el-table-column>
          <el-table-column
            label="实收"
            width="100"
            align="right"
            prop="amountPaid"
          >
          </el-table-column>
          <el-table-column
            label="优惠"
            width="100"
            align="right"
            prop="discount"
          >
          </el-table-column>
          <el-table-column
            align="center"
            width="100"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a @click="delProduct(row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" style="margin-top: 20px" @click="addProduct">添加规格</el-button>
        <el-button type="primary" style="margin-top: 20px" :loading="clicked" @click="updateClick('warehouseForm')">保存
        </el-button>
      </el-form>
      <el-dialog
        title="新增商品"
        :visible.sync="procuctVisible"
        width="68%"
        v-el-drag-dialog
        :before-close="productClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="添加品牌"
        :visible.sync="orderVisible"
        width="68%"
        v-el-drag-dialog
        :before-close="orderClose">
        <div style="position: relative;">
          <productTable ref="productList" @doubleClick="doubleClick" @addClick="addClick"></productTable>
        </div>
      </el-dialog>
      <el-dialog
        title="新增客户"
        :visible.sync="memberVisible"
        width="80%"
        v-el-drag-dialog
        append-to-body
        :before-close="memberClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <memberAdd :memberType="memberType" @memberClick="memberClick"></memberAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="queryType"
        width="80%"
        v-el-drag-dialog
        append-to-body
        :before-close="queryClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
        </div>
      </el-dialog>
      <el-dialog
        title="选择地址"
        :visible.sync="receiverType"
        width="80%"
        v-el-drag-dialog
        append-to-body
        :before-close="receiverClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <receiverList :key="memberId" :memberId="memberId" @receiverClick="receiverClick"></receiverList>
        </div>
      </el-dialog>
      <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    </el-main>
  </el-container>
</template>
<script>
  import {EventBus} from '@/api/eventBus'
  import {list as productList} from '@/api/product'
  import {list as memberList} from '@/api/member'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import {update,find} from '@/api/warehouse'
  import utils from '../../utils/utils.js'
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from './components/productList'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import memberAdd from '@/views/member/add'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'
  import receiverList from './components/receiverList'
  export default {
    directives: {elDragDialog},
    name: 'warehouse-edit',
    data() {
      return {
        clicked: false, // 按钮防双击
        form: {
          memberId: '',
          createDate: new Date(),
          operatorId: '',
          officeId: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          memo: '',
          consignee: '',
          phone: '',
          subPrice: 0,
          subQuantity: 0,
          taxType: '0',
          sn:'',
          id:'',
        },
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        listForm: [],
        tableIndex: '',
        procuctVisible: false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        district: {province: 440000, city: '广州市', area: '海珠区'},
        memberName: '',
        memberList: [],
        memberVisible: false,
        memberType: 'add',
        sysEmployeeList: [],
        operatorName: '',
        officeName: '',
        rules: {
          memberId: [
            {required: true, message: '请选择客户', trigger: 'blur'},
          ],
          areaId: [
            {required: true, message: '请选择所在地', trigger: 'blur'}
          ],
          // address: [
          //   {required: true, message: '请输入详细地址', trigger: 'blur'}
          // ],
          consignee: [
            {required: true, message: '请输入收货人', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入联系电话', trigger: 'blur'}
          ]
        },
        queryType: false,
        findByList: [],
        receiverType: false,
        memberId: ''
      }
    },
    created() {
      var _this = this;
      _this.form.id = this.$route.query.id;
      find(this.$route.query.id).then(response => {
        console.log(response);
        _this.form.memberId = response.data.memberId;
        _this.memberName = response.data.memberId;
        _this.form.createDate = response.data.createDate;
        _this.form.operatorId = response.data.operatorId;
        _this.operatorName = response.data.operatorId;
        _this.form.officeId = response.data.officeId;
        _this.officeName = response.data.officeId;
        _this.form.address = response.data.address;
        _this.form.areaName = response.data.areaName;
        _this.form.areaId = response.data.areaId;
        _this.district = utils.decodeArea(response.data.areaId.toString());
        _this.form.memo = response.data.memo;
        _this.form.consignee = response.data.consignee;
        _this.form.phone = response.data.phone;
        _this.form.subPrice = response.data.subPrice;
        _this.form.subQuantity = response.data.subQuantity;
        _this.form.taxType = JSON.stringify(response.data.taxType);
        _this.productList = response.data.itemList;
        _this.form.sn = response.data.sn
      }).catch(error => {
      })
      this.loadlist();
      this.loadMember();
      this.loadSysEmployee();
    },
    components: {
      productAdd, productTable, Distpicker, memberAdd, OfficeDialog, productRadio, receiverList
    },
    methods: {
      //删除商品列表
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }
      },
      //新增商品
      addProduct() {
        this.productList.push({
          productId: '',
          name: '',
          sn: '',
          price: '',
          orders: '',
          quantity: '',
          subTotal: '',
          amountPaid: 0,
          spec: '',
          discount: 0,
          cost: 0,
          unit: ''
        })
      },
      //商品总数据
      loadlist() {
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.keyword.sn)
        productList(params).then(response => {
          console.log(response);
          _this.listForm = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //更多商品弹出
      moreProductClick() {
        var _this = this;
        _this.orderVisible = true;
      },
      doubleClick(data) {
        this.productList.push(data)
        this.procuctFilter();
        // this.calculateClick()
      },
      addClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          _this.productList.push(item)
        });
        this.procuctFilter();
        // this.calculateClick()
      },
      orderClose() {
        this.orderVisible = false;
        this.$refs.productList.cancelClick();
      },
      //商品表下拉选择
      selectClick(index) {
        var _this = this
        if (index == '#') {
          _this.procuctVisible = true;
        } else {
          var goodsDetails = {
            productId: _this.listForm[index].id,
            name: _this.listForm[index].name,
            sn: _this.listForm[index].sn,
            cost: _this.listForm[index].cost,
            price: _this.listForm[index].price,
            orders: _this.listForm[index].orders,
            subTotal: _this.listForm[index].price,
            unit: _this.listForm[index].unit,
            spec: _this.listForm[index].spec1 + _this.listForm[index].spec2,
            amountPaid: 0,
            discount: 0,
            quantity: 1
          };
          _this.productList[_this.tableIndex] = goodsDetails
        }
        this.procuctFilter();
      },
      //获取当前点击商品表行
      tableClick(data) {
        this.tableIndex = this.productList.indexOf(data);
        this.chooseOrderName = this.productList[this.tableIndex].name
      },
      //新增商品弹窗
      productClose() {
        this.procuctVisible = false;
        this.productList[this.tableIndex].name = this.chooseOrderName
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      //商品过滤
      procuctFilter() {
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          var key = this.productList[i].productId;
          if (temp[key]) {
            temp[key].productId = temp[key].productId;
            temp[key].quantity = temp[key].quantity + this.productList[i].quantity;
            temp[key].subTotal = (parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity)).toFixed(2);
            temp[key].amountPaid = temp[key].subTotal
          } else {
            temp[key] = {};
            temp[key].productId = this.productList[i].productId;
            temp[key].quantity = this.productList[i].quantity;
            temp[key].subTotal = (parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity)).toFixed(2);
            temp[key].amountPaid = temp[key].subTotal
          }
          temp[key].name = this.productList[i].name;
          temp[key].sn = this.productList[i].sn;
          temp[key].price = this.productList[i].price;
          temp[key].cost = this.productList[i].cost;
          temp[key].orders = this.productList[i].orders;
          temp[key].discount = this.productList[i].discount;
          temp[key].spec = this.productList[i].spec;
          temp[key].unit = this.productList[i].unit
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
        console.log(newfood)
      },
      //订单保存
      updateClick(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
              };
              itemList.push(goodsDetails)
            });
            _this.form.subPrice = _this.productList.reduce(function (totle, item) {
              return totle + (item.quantity * item.price)
            }, 0)
            _this.form.subQuantity = _this.productList.reduce(function (totle, item) {
              return totle + item.quantity
            }, 0)
            let formData = {
              memberId: _this.form.memberId,
              createDate: _this.form.createDate,
              operatorId: _this.form.operatorId,
              officeId: _this.form.officeId,
              areaName: _this.form.areaName,
              address: _this.form.address,
              areaId: _this.form.areaId,
              memo: _this.form.memo,
              phone: _this.form.phone,
              consignee: _this.form.consignee,
              warehouseType: 4,
              subPrice: _this.form.subPrice,
              subQuantity: _this.form.subQuantity,
              shopId: 1,
              supplierId: 1,
              taxType: _this.form.taxType,
              sn:_this.form.sn,
              id:_this.form.id,
              itemList: itemList,
            };
            update(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('warehouse-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/warehouse/view',query: {id: _this.form.id}
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      //地址选择
      onSelected(val) {
        if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
          this.form.areaId = val.area.code;
          this.form.areaName = val.area.value;
        }
      },
      //会员选择
      loadMember() {
        var _this = this
        let params = new URLSearchParams();
        memberList(params).then(response => {
          console.log(response);
          _this.memberList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectMember(data) {
        console.log(data)
        var _this = this
        if (data == '#') {
          _this.memberVisible = true;
        } else {
          _this.form.memberId = data.id
          if (!utils.isNull(data.areaId)) {
            _this.form.address = data.address
            _this.form.areaName = data.areaName
            _this.form.areaId = data.areaId;
            _this.district = utils.decodeArea(data.areaId.toString());
          } else {
            _this.form.address = '';
            _this.form.areaName = '广州市,海珠区';
            _this.form.areaId = '440000';
            _this.district = utils.decodeArea('440000');
          }
        }
      },
      memberClose() {
        this.memberVisible = false;
        this.memberName = '';
      },
      memberClick(data) {
        var _this = this;
        _this.memberName = data.name;
        _this.form.memberId = data.id;
        _this.memberVisible = false;
      },
      //  业务员
      loadSysEmployee() {
        var _this = this
        let params = new URLSearchParams();
        sysEmployeeList(params).then(response => {
          console.log(response);
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectSysEmployee(data) {
        this.form.operatorId = data
      },
      //  销售公司
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },
      //  地址选择
      loadReceiver() {
        var _this = this
        this.memberId = this.form.memberId
        this.receiverType = true
        console.log(this.memberId)
      },
      receiverClose() {
        this.receiverType = false
      },
      receiverClick(data) {
        console.log(data)
        var _this = this
        _this.form.address = data.address;
        _this.form.areaName = data.areaName;
        _this.form.areaId = data.areaId;
        _this.district = utils.decodeArea(data.areaId.toString());
        _this.receiverType = false
      },
      //刷新商品合计
      refreshClick() {
        this.procuctFilter()
      },
      queryClick() {
        console.log('1111')
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.query.sn);
        findBySn(params).then(response => {
          console.log(response)
          if (response.data.products.length == 1) {
            var goodsDetails = {
              productId: response.data.products[0].id,
              name: response.data.products[0].name,
              sn: response.data.products[0].sn,
              cost: response.data.products[0].cost,
              price: response.data.products[0].price,
              orders: response.data.products[0].orders,
              subTotal: response.data.products[0].price,
              spec: response.data.products[0].spec1 + response.data.products[0].spec2,
              amountPaid: 0,
              discount: 0,
              quantity: 1,
              unit: response.data.products[0].unit
            };
            _this.productList.push(goodsDetails)
            _this.procuctFilter()
          } else if (response.data.products.length > 1) {
            _this.findByList = response.data.products
            _this.queryType = true
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      queryClose() {
        this.queryType = false
      },
      findByClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          _this.productList.push(item)
        });
        this.queryType = false
        this.procuctFilter();
      },
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }

  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
